'''
Created on Jun 6, 2015

@author: geo
'''
import os
import re
import feedparser as fp

#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # use django envronment

from django.db import IntegrityError
from mokitech.models import Album as Al
from mokitech.models import Artist as Ar

class Rss(object):
    '''
    classdocs
    '''

    def __init__(self, url):
        '''
        Constructor
        '''
        self.rss = fp.parse(url)
        self.data = ['artist', 'artistlink', 
                     'album', 'albumlink', 'albumprice',
                     'releasedate']
        self.reo = re.compile(r'<img\sborder.*src="(.*)"\s/>') # search itms_coverart

    def get_items(self):
        items = []
        for item in self.rss.entries:
            rs = {}
            for each_data in self.data:
                rs[each_data] = item['itms_%s' %each_data]
            rs['genre'] = item.tags[0]['term']
            rs['coverart'] = self.reo.search(item['content'][0]['value']).groups()[0]
            items.append(rs)
        return items
  
class SetData(object): 
    def __init__(self, data):
        self.data = data
    
    def set_data(self):
        for data in self.data:
            ar = Ar(name = data['artist'], link = data['artistlink'])
            try:
                ar.save()
            except IntegrityError: # if the artist already exist in the table, then get the id
                ar = Ar.objects.get(name = data['artist'])
            al = Al(name = data['album'], link = data['albumlink'],
                    artist = ar, price = data['albumprice'], genre = data['genre'], 
                    cover_art = data['coverart'], release_date = data['releasedate'])
            try:
                al.save()
            except IntegrityError: # if the artist already exist in the table, just pass
                pass
            
def main(): 
    rss = Rss(r'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStore.woa/wpa/MRSS/newreleases/limit=300/rss.xml')
    r = rss.get_items()
    for k, v in r[0].iteritems():
        print k, v
    SetData(r).set_data()

if __name__ == '__main__':
    main()